﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.HCLoad.Parameters;
using YArchitech.HCLoad.Properties;
using YArchitech.HCLoad.Utils;
using YArchitech.LIB;

namespace YArchitech.HCLoad.Query
{
	public partial class QueryForm : System.Windows.Forms.Form
	{
		public QueryForm(Space space)
		{
			this.m_Space = space;
			this.InitializeComponent();
			this.m_SpaceAttributeFile = new SpaceAttributeFile();
		}

		private void QueryForm_Load(object sender, EventArgs e)
		{
			base.Icon = Resource.YArchitechIcon;
			this.button_OK.Hide();
			base.StartPosition = FormStartPosition.CenterParent;
			this.m_SpaceAttributeFile.Load(HcUtils.SpaceParametersFile);
			PropertyGridAttritutes selectedObject = new PropertyGridAttritutes(this.m_SpaceAttributeFile);
			this.propertyGrid_Attribute.SelectedObject = selectedObject;
			this.ShowSpaceData(this.m_Space);
		}

		private void button_OK_Click(object sender, EventArgs e)
		{
			base.DialogResult = DialogResult.OK;
			base.Close();
		}

		private void button_Cancel_Click(object sender, EventArgs e)
		{
			base.DialogResult = DialogResult.Cancel;
			base.Close();
		}

		private void button_PickSpace_Click(object sender, EventArgs e)
		{
			this.button_OK_Click(null, null);
		}

		private void ShowSpaceData(Space space)
		{
			if (space == null || this.propertyGrid_Attribute == null)
			{
				return;
			}
			PropertyGridAttritutes propertyGridAttritutes = this.propertyGrid_Attribute.SelectedObject as PropertyGridAttritutes;
			if (propertyGridAttritutes != null)
			{
				propertyGridAttritutes.Attach(space);
			}
			this.propertyGrid_Attribute.Refresh();
		}

		public static void SelectAndShowSpace(UIApplication rvtUIApp)
		{
			try
			{
				for (;;)
				{
					UIDocument activeUIDocument = rvtUIApp.ActiveUIDocument;
					RevitVersionFuncs.ClearSelection(activeUIDocument.Selection);
					string propmt_PICKSPACE = YArchitech.HCLoad.Properties.Resources.PROPMT_PICKSPACE;
					Reference reference = activeUIDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, new HcSpaceFilter(), propmt_PICKSPACE);
					if (reference != null)
					{
						Element element = activeUIDocument.Document.GetElement(reference);
						if (element is Space)
						{
							QueryForm queryForm = new QueryForm(element as Space);
							if (DialogResult.OK != queryForm.ShowDialog())
							{
								break;
							}
						}
					}
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
			}
		}

		private Space m_Space;

		private string sYArchitechSpaceParametersFile = HcUtils.SpaceParametersFile;

		private SpaceAttributeFile m_SpaceAttributeFile;
	}
}
